package com.example.happ.controller;

import com.example.happ.pojo.User;
import com.example.happ.service.UserService;
import javax.annotation.Resource;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * @Package：com.example.demo.controller
 * @Project：demo
 * @name：王志迎
 * @Date：2024/12/24 9:13
 * @Filename：saveUser
 *
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;
    private final String APPID = "wx28674d4f41a7bd61";
    private final String SECRET = "758e556ad75888318984c311c0a05260";
    private final String WX_API_URL = "https://api.weixin.qq.com/sns/jscode2session";

    @RequestMapping("/login")//保存用户信息请求
    public int saveMerchantByCode(@RequestBody Map<String,String> codeMap){
        int success=0;
        String code= codeMap.get("code");
        String avatarUrl= codeMap.get("avatarUrl");
        String nickName= codeMap.get("nickname");
        String phone= codeMap.get("phone");
        System.out.println(codeMap);
        if (code == null || code.isEmpty()) {
            throw new RuntimeException("code不能为空");
        }
        // 拼接请求URL
        String requestUrl=String.format("%s?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",WX_API_URL,APPID,SECRET,code);
        // 发送HTTP请求
        RestTemplate restTemplate = new RestTemplate();
        String response = restTemplate.getForObject(requestUrl, String.class);
        //解析返回结果
        ObjectMapper objectMapper= new ObjectMapper();
        try {
            Map<String,Object> result=objectMapper.readValue(response,Map.class);
            if (result.containsKey("errcode")) {
                throw new RuntimeException("微信登录失败：" + result.get("errmsg"));
            }
            String openId=(String) result.get("openid");
            System.out.println(openId);
            success=userService.insertUserInformationByOpenid(openId,avatarUrl,nickName,phone);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("解析微信接口响应失败", e);
        }
        return success;
    }
    @RequestMapping("/find")//用户登录查有没有用户信息
    @CrossOrigin(origins = "http://localhost:8080")
    public int findMerchantByCode(@RequestBody Map<String,String> codeMap){
        int success=0;
        String code= codeMap.get("code");
        if (code == null || code.isEmpty()) {
            throw new RuntimeException("code不能为空");
        }
        String openId;
        String requestUrl=String.format("%s?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",WX_API_URL,APPID,SECRET,code);
        RestTemplate restTemplate = new RestTemplate();
        String response = restTemplate.getForObject(requestUrl, String.class);
        ObjectMapper objectMapper= new ObjectMapper();
        try {
            Map<String,Object> result=objectMapper.readValue(response,Map.class);
            if (result.containsKey("errcode")) {
                throw new RuntimeException("微信登录失败：" + result.get("errmsg"));
            }
            openId=(String) result.get("openid");
            System.out.println(openId);

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("解析微信接口响应失败", e);
        }
        success=userService.findUserInformationByOpenid(openId);
        System.out.println(success);
        return success;
    }

    /**
     * 保存用户信息
     * @param
     * @return
     */
    // 更新用户信息
    @RequestMapping("/update")
    @CrossOrigin(origins = "http://localhost:8080")
    public Boolean updateUserInfo(@RequestBody Map<String,String> codeMap) {
        boolean success =false;
        success = userService.updateUserInfo(codeMap);
        return success;
    }

    // 获取用户信息
    @RequestMapping("/select")//查用户信息返回用户信息
    @CrossOrigin(origins = "http://localhost:8080")
    public User getUserInfo(@RequestBody Map<String,Integer> codeMap) {
        System.out.println("查用户信息返回用户信息收到的数据0:"+codeMap.get("id"));
        return userService.getUserInfo(codeMap.get("id"));
    }

}
